import React, { useEffect, useState } from 'react';
import {
  Tabs,
  Input,
  Form,
  DatePicker,
  ConfigProvider,
  Select,
  Button,
  Divider,
  Pagination,
  Checkbox,
  PaginationProps,
  Card,
  Table,
  message,
} from 'antd';
import {
  searchReport,
  getReportInfoById,
  saveReport,
} from '@/api/game_report_controller';
import styles from './index.less';
import dayjs from 'dayjs';
import { history, KeepAlive } from 'umi';
import { CloseOutlined } from '@ant-design/icons';
import exportlog from '../../../../assets/exportlog.png';

const { Option } = Select;
const { Search } = Input;
const { TextArea } = Input;

const MyReportManage = (props) => {
  const [oldBaselineCardList, setOldBaselineCardList] = useState([]);
  // 基线卡片列表
  const [baselineCardList, setBaselineCardList] = useState([]);
  // 当前选中卡片的reportID
  const [selectedCardId, setSelectCard] = useState('');
  const [testName, setTestName] = useState('');
  const [testObjectiveInput, setTestObjectiveInput] = useState('');
  const [softwareVersion, setSoftwareVersion] = useState('');
  const [reportTypesList, setReportTypesList] = useState([]);
  // 报告类型选中值
  const [reportTypeValue, setReportType] = useState('');
  // 报告名称选中值-非必填项
  const [reportNameValue, setReportName] = useState('');
  // 只显示我的报告
  const [myselfValue, setMyself] = useState('');
  // 基本信息-报告名称
  const [baseReportName, setBaseReportName] = useState('');
  // 基本信息-测试目的
  const [baseReportVersion, setBaseReportVersion] = useState('');
  // 基本信息-软件版本
  const [baseSoftVersion, setBaseSoftVertion] = useState('');
  // 基本信息-硬件版本
  const [baseHardWareVersion, setHardWareVersion] = useState('');

  // const onSearch = (value) => {
  //   let arr = [];
  //   if (value !== '') {
  //     for (let i = 0; i < baselineCardList.length; i++) {
  //       if (baselineCardList[i].id.indexOf(value) != -1) {
  //         arr.push(baselineCardList[i]);
  //       }
  //     }
  //     setBaselineCardList(arr);
  //   } else {
  //     setBaselineCardList(oldBaselineCardList);
  //   }
  // };

  useEffect(() => {
    settableData(tableData);
  }, [tableData]);

  useEffect(() => {
    let arr = [];
    for (let i = 0; i < 8; i++) {
      const serialNo = i.toString();
      arr.push({
        id: serialNo,
        name: `${serialNo}音视频测试-视频流畅性测试`,
        date: `2023-05-31 16:00:00`,
        personnelNo: `${serialNo}${serialNo}${serialNo}${serialNo}`,
      });
    }
    setOldBaselineCardList(arr);
    // setBaselineCardList(arr);
    reportTypesListGet();
  }, []);
  const showTotal = (total) => `Total ${total} items`;
  const addProblem = (e) => {
    console.log('111');
    tableData.push({ key: tableData.length + 1 });
    console.log(tableData);
    settableData([...tableData]);
  };
  const deleteProblem = (record, index) => {
    console.log('record', record);
    // settableData(tableData.filter(a => a.key !== record.key));
    const newData = tableData.filter((item) => item.key !== record.key);
    settableData(newData);
  };
  const handleTextChangeProblem = (e, record) => {
    //tableData[index].problem=event.target.value;
    const { value } = e.target;
    const newData = [...tableData];
    const index = newData.findIndex((item) => record.key === item.key);
    if (index > -1) {
      newData[index].description = value;
      settableData(newData);
    }
  };
  const handleTextChangeLog = (e, record) => {
    //tableData[index].problem=event.target.value;
    const { value } = e.target;
    const newData = [...tableData];
    const index = newData.findIndex((item) => record.key === item.key);
    if (index > -1) {
      newData[index].archivePath = value;
      settableData(newData);
    }
  };
  const clickCardBtn = async (item, index) => {
    setSelectCard(item.reportId);
    const resp = await getReportInfoById({
      projectId: '614',
      reportId: item.reportId,
    });
    console.log('-----------(根据id获取报告信息)', resp);
  };
  const [tableData, settableData] = useState([]);
  const [detailData, setDetailData] = useState([
    {
      key: 1,
      phone: 'info1',
      testVersion: '1',
    },
    {
      key: 2,
      phone: 'info2',
      testVersion: '2',
    },
  ]);
  const columns = [
    {
      title: '问题描述',
      dataIndex: 'problem',
      key: 'problem',
      render: (_, record, index) => (
        <TextArea
          style={{ width: '100%' }}
          // value={tableData[index].problem}
          onChange={(e) => {
            handleTextChangeProblem(e, record);
          }}
        ></TextArea>
      ),
    },
    {
      title: 'log与systrace归档路径',
      dataIndex: 'log',
      key: 'log',
      render: (_, record, index) => (
        <TextArea
          style={{ width: '100%' }}
          // value={tableData[index].log}
          onChange={(e) => {
            handleTextChangeLog(e, record);
          }}
        ></TextArea>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, record, index) => (
        <a
          onClick={() => {
            deleteProblem(record, index);
          }}
        >
          删除
        </a>
      ),
    },
  ];
  const columnsDetail = [
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: () => <a>Delete</a>,
      width: 100,
    },
    {
      title: '基础信息',
      dataIndex: 'baseInfo',
      key: 'baseInfo',
      children: [
        {
          title: '测试手机',
          dataIndex: 'phone',
          key: 'phone',
          width: 100,
        },
        {
          title: '测试版本',
          dataIndex: 'testVersion',
          key: 'testVersion',
          width: 100,
        },
        {
          title: '测试游戏',
          dataIndex: 'testGame',
          key: 'testGame',
          width: 100,
        },
        {
          title: '游戏版本',
          dataIndex: 'gameVersion',
          key: 'gameVersion',
          width: 100,
        },
        {
          title: '满帧',
          dataIndex: 'fullFrame',
          key: 'fullFrame',
          width: 100,
        },
      ],
    },
    {
      title: '关键数据',
      dataIndex: 'keyData',
      key: 'keyData',
      children: [
        {
          title: '平均帧率',
          dataIndex: 'averageFrame',
          key: 'averageFrame',
          width: 100,
        },
        {
          title: '低帧率',
          dataIndex: 'lowFrame',
          key: 'lowFrame',
          width: 100,
        },
        {
          title: '抖动率',
          dataIndex: 'jitterRate',
          key: 'jitterRate',
          width: 100,
        },
        {
          title: '每小时卡顿次数',
          dataIndex: 'numberHour',
          key: 'numberHour',
          width: 100,
        },
        {
          title: '最差丢帧',
          dataIndex: 'lostFrame',
          key: 'lostFrame',
          width: 100,
        },
        {
          title: '归一化电流',
          dataIndex: 'normalizedCurrent',
          key: 'normalizedCurrent',
          width: 100,
        },
        {
          title: '分辨率',
          dataIndex: 'resolutionRatio',
          key: 'resolutionRatio',
          width: 100,
        },
        {
          title: '游戏版本',
          dataIndex: 'gameVersion',
          key: 'gameVersion',
          width: 100,
        },
      ],
    },
    {
      title: '辅助数据',
      dataIndex: 'auxiliaryata',
      key: 'auxiliaryata',
      children: [
        {
          title: '链接',
          dataIndex: 'link',
          key: 'link',
          render: () => <a>报告详情</a>,
          width: 100,
        },
        {
          title: '环境温度',
          dataIndex: 'ambientTemperature',
          key: 'ambientTemperature',
          width: 100,
        },
        {
          title: 'shell最低温度',
          dataIndex: 'shellLow',
          key: 'shellLow',
          width: 100,
        },
        {
          title: 'shell最高温度',
          dataIndex: 'shellHigh',
          key: 'shellHigh',
          width: 100,
        },
        {
          title: 'system_h最低温度',
          dataIndex: 'systemLow',
          key: 'systemLow',
          width: 100,
        },
        {
          title: 'system_h最高温度',
          dataIndex: 'systemHigh',
          key: 'systemHigh',
          width: 100,
        },
        {
          title: '壳温升温',
          dataIndex: 'shellRise',
          key: 'shellRise',
          width: 100,
        },
        {
          title: '前10分钟温长',
          dataIndex: 'durationTen',
          key: 'durationTen',
          width: 100,
        },
        {
          title: '低温时长占比',
          dataIndex: 'durationLow',
          key: 'durationLow',
          width: 100,
        },
        {
          title: '最小帧',
          dataIndex: 'minFrame',
          key: 'minFrame',
          width: 100,
        },
        {
          title: '测试方式',
          dataIndex: 'testType',
          key: 'testType',
          width: 100,
        },
        {
          title: '测试人员',
          dataIndex: 'testers',
          key: 'testers',
          width: 100,
        },
        {
          title: '测试时间',
          dataIndex: 'testTime',
          key: 'testTime',
          width: 100,
        },
        {
          title: '游戏时长(分钟)',
          dataIndex: 'gameTime',
          key: 'gameTime',
          width: 100,
        },
        {
          title: 'CPU-C1(频率)',
          dataIndex: 'CPU-C1',
          key: 'CPU-C1',
          width: 100,
        },
        {
          title: 'CPU-C2(频率)',
          dataIndex: 'CPU-C2',
          key: 'CPU-C2',
          width: 100,
        },
        {
          title: 'CPU-C3(频率)',
          dataIndex: 'CPU-C3',
          key: 'CPU-C3',
          width: 100,
        },
        {
          title: 'GPU(频率)',
          dataIndex: 'GPU',
          key: 'GPU',
          width: 100,
        },
        {
          title: 'DDR(频率)',
          dataIndex: 'DDR',
          key: 'DDR',
          width: 100,
        },
        {
          title: '备注',
          dataIndex: 'note',
          key: 'note',
          width: 100,
        },
      ],
    },
  ];
  const deleteCardBtn = (val) => {
    // 处理删除操作
    console.log('-----------(删除卡片)', val);
    const newData = baselineCardList.filter((item) => item.id !== val.id);
    setBaselineCardList(newData);
  };
  const searchCardListBtn = async (value) => {
    const par = {
      projectId: '614',
      reportName: reportNameValue,
      page: '1',
      pageSize: '10',
      reportType: reportTypeValue,
      myself: myselfValue,
      userId: '',
    };
    const { data } = reportTypeValue
      ? await searchReport(par)
      : message.warning('请选择报告类型！');
    data ? setBaselineCardList(data.data.myselfReportList) : '';
    console.log('-----------(查询按钮获取卡片列表)', baselineCardList);
  };
  const reportTypesListGet = (value) => {
    let reportTypes = [
      {
        value: 'All',
        label: 'All',
      },
      {
        value: '版本报告',
        label: '版本报告',
      },
      {
        value: '对比报告',
        label: '对比报告',
      },
    ];
    setReportTypesList([...reportTypes]);
  };
  const saveReportBtn = async () => {
    // 保存报告
    const par = {
      reportId: '',
      projectId: '614',
      reportName: baseReportName,
      softVersion: baseSoftVersion,
      hardwareVersion: baseHardWareVersion,
      versionGoal: '',
      newQuestions: tableData,
      reportCondition: {
        baseline: '',
        compareUpVersion: '',
        testTeam: '',
        testMethod: '',
        versions: '',
        gameName: '',
      },
    };
    const resp = selectedCardId
      ? await saveReport(par)
      : message.warning('请选择报告');
  };

  return (
    <div className={styles.reportContainer}>
      <div className={styles.messageCard}>
        <div className={styles.title}>
          <div className={styles.title_black}></div>
          报告列表
        </div>

        <div className={styles.smallTable}>
          <div className={styles.type}>
            <label className={styles.column_title}>报告类型</label>
            <Select
              allowClear
              className={styles.select_type}
              options={reportTypesList}
              onChange={(val) => {
                setReportType(val);
              }}
            />
          </div>

          <div className={styles.name}>
            <Input
              allowClear
              placeholder="输入报告名称进行搜索(非必填)"
              className={styles.input_type}
              // onSearch={(val) => {
              //   console.log("-----------(这个事件触发了吗？)", val);
              // }}
              onChange={(val) => {
                setReportName(val.nativeEvent.target.value);
              }}
            />
          </div>
          <div className={styles.check}>
            <Checkbox
              className={styles.checkbox_type}
              onChange={(e) => {
                setMyself(e.target.checked);
              }}
            >
              只显示我创建的报告
            </Checkbox>
          </div>
          <div className={styles.query}>
            <Button
              className={styles.bt_query}
              type="primary"
              onClick={searchCardListBtn}
            >
              查询
            </Button>
          </div>
          <div className={styles.query}>
            <Button className={styles.bt_query} type="primary">
              复制报告链接
            </Button>
          </div>
        </div>

        <div className={styles.divCard}>
          <div className={styles.cardTable}>
            {baselineCardList?.map((item, index) => {
              const { reportId, reportName, time } = item;
              return (
                <Card
                  key={index}
                  // className={styles.single_card}
                  className={`${styles.single_card} ${
                    selectedCardId === reportId ? styles.card_selected : ''
                  }`}
                  onClick={() => clickCardBtn(item, index)}
                >
                  <Button type="text" onClick={() => deleteCardBtn(item)}>
                    <CloseOutlined />
                  </Button>
                  <img className={styles.exportImg} src={exportlog}></img>
                  <div className={styles.card_first}>
                    <span className={styles.first_title}>{reportName}</span>
                  </div>
                  <div className={styles.card_lable}>
                    <span className={styles.label_name}>日期</span>
                    <span className={styles.label_cont}>{time}</span>
                  </div>

                  <div className={styles.card_lable}>
                    <span className={styles.label_name}>人员编号</span>
                    {/* <span className={styles.label_cont}>{personnelNo}</span> */}
                  </div>
                  {/* <Divider style={{ marginTop: '10px', marginBottom: '10px' }}></Divider> */}
                  <div className={styles.card_button}>
                    {/* <div className={styles.button_look} onClick={() => toReportPage(item.id)}>查看报告</div>
                <div className={styles.button_delect} onClick={() => delectReport(item.id)}>删除</div> */}
                  </div>
                </Card>
              );
            })}
          </div>
        </div>
        <div className={styles.page}>
          <Pagination
            total={85}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `Total ${total} items`}
          />
        </div>

        <div className={styles.title}>
          <div className={styles.title_black}></div>
          基本信息
        </div>

        <div className={styles.baseTable}>
          <div className={styles.tableColumn}>
            <div className={styles.column_label}>
              <label className={styles.column_title}>报告名称</label>
              <Input
                allowClear
                placeholder=""
                className={styles.input_info}
                // value={testName}
                onChange={(val) => {
                  setBaseReportName(val.nativeEvent.target.value);
                  console.log('-----------(报告名称)', val);
                }}
              />
            </div>
          </div>
          <div className={styles.tableColumnNext}>
            <div className={styles.column_label}>
              <label className={styles.column_title}>测试目的</label>
              <Input
                allowClear
                placeholder=""
                className={styles.input_info}
                // value={testObjectiveInput}
              />
            </div>
            <div className={styles.column_label}>
              <label className={styles.column_title}>软件版本</label>
              <Input
                allowClear
                placeholder=""
                className={styles.input_info}
                // value={testName}
                onChange={(val) => {
                  setBaseSoftVertion(val.nativeEvent.target.value);
                  console.log('-----------(软件版本)', val);
                }}
              />
            </div>

            <div className={styles.column_label}>
              <label className={styles.column_title}>硬件版本</label>
              <Input
                allowClear
                placeholder=""
                className={styles.input_info}
                // value={hardwareVersion}
                onChange={(val) => {
                  setHardWareVersion(val.nativeEvent.target.value);
                  console.log('-----------(硬件版本)', val);
                }}
              />
            </div>
          </div>
        </div>

        <div className={styles.title}>
          <div className={styles.title_black}></div>
          测试结论
        </div>

        <div className={styles.resultTable}>
          <div className={styles.newly}>
            <Button className={styles.btn_add} onClick={addProblem}>
              新增问题
            </Button>
          </div>
          <Table
            columns={columns}
            dataSource={tableData}
            className={styles.table_style}
            pagination={false}
          ></Table>
        </div>

        <div className={styles.title}>
          <div className={styles.title_black}></div>
          详细数据
        </div>

        <div className={styles.detailTable}>
          <Table
            className={styles.table_top}
            pagination={false}
            columns={columnsDetail}
            dataSource={detailData}
            scroll={{
              x: 'calc(700px + 50%)',
              y: 240,
            }}
          ></Table>
        </div>
        <div className={styles.footer}>
          <Button
            type="primary"
            className={styles.bt_style}
            onClick={saveReportBtn}
          >
            保存报告
          </Button>
          <Button className={styles.exportBtn} type="primary">
            导出报告
          </Button>
        </div>
      </div>
    </div>
  );
};

export default MyReportManage;
